package wwl.lsf.hellospringboot.test.nio.netty聊天;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ChatServer {

  private int port;

  public ChatServer(int port) {
    this.port = port;
  }


  public void run() throws InterruptedException {

    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      ServerBootstrap serverBootstrap;
      serverBootstrap = new ServerBootstrap();
      serverBootstrap.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {

              ChannelPipeline pipeline = socketChannel.pipeline();
              pipeline.addLast("decoder", new StringDecoder());

              pipeline.addLast("encoder", new StringEncoder());

              pipeline.addLast("handler", new ChatServerHandler());


            }
          }).option(ChannelOption.SO_BACKLOG, 128)
          .childOption(ChannelOption.SO_KEEPALIVE, true);
      System.out.println("netty Chat Server 启动");

      ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

      channelFuture.channel().closeFuture().sync();
    } finally {

      workerGroup.shutdownGracefully();
      bossGroup.shutdownGracefully();

      System.out.println("服务器关闭了");


    }

  }

  public static void main(String[] args) throws InterruptedException {

    new ChatServer(9999).run();

  }
}
